package com.zhkj.txg.module.login.ui

import android.app.Activity
import android.content.Intent
import android.text.Html
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.txg.R
import com.zhkj.txg.module.login.vm.LoginViewModel
import kotlinx.android.synthetic.main.activity_agreement.*

const val AGREE = "agree"

class UserAgreementActivity : ViewModelActivity<LoginViewModel>() {

    companion object {
        private val TYPE = "type"
        fun startForResult(fragment: Fragment, requestCode: Int) {
            val intent = Intent(fragment.activity, UserAgreementActivity::class.java)
                .putExtra(TYPE, 0)
            fragment.startActivityForResult(intent, requestCode)
        }

        fun normal(activity: Activity) {
            val intent = Intent(activity, UserAgreementActivity::class.java)
                .putExtra(TYPE, 1)
            activity.startActivity(intent)
        }
    }

    override val layoutResId: Int = R.layout.activity_agreement
    override fun setViewModel(): LoginViewModel = createViewModel()
    override fun statusTitleBar(): View? = titleAgreement

    override fun initUI() {
        btnConfirm.setOnClickListener {
            intent.putExtra(AGREE, true)
            setResult(Activity.RESULT_OK, intent)
            finish()
        }
        val type = intent.getIntExtra(TYPE, 0)
        if (type == 1) btnConfirm.visibility = View.GONE
    }

    override fun initData() {
        viewModel.userAgreement().takeIf {
            !it.hasObservers()
        }?.observe(this, Observer {
            handlerResponseStatus(it.status, it.statusTip)
            when (it.status) {
                HttpResponseStatus.Status.SUCCESS -> {
                    tvAgreement.text = Html.fromHtml(it.response?.data?.content)
                }
                HttpResponseStatus.Status.FAILURE -> {
                    finish()
                }
                else -> Unit
            }
        })
    }
}